import sys
import requests
import time
import logging
from playwright.async_api import async_playwright
import asyncio
import json

# 修改打印语句以强制刷新输出缓冲区，服务器日志不打印的bug。
sys.stdout.reconfigure(line_buffering=True)


# 获取文件名
log_file = sys.argv[1] if len(sys.argv) > 1 else "default.log"
# 配置日志记录
logging.basicConfig( filename='./logs/'+log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

async def send_to_api(data, data_type, url):
    # api_url = 'https://yunlvltd.com/app-api/vote/test/println'  # 替换为你的 API URL
    api_url = 'http://172.21.0.7:48080/app-api/vote/test/println'  # 替换为你的 API URL
    # api_url = 'http://127.0.0.1:48080/app-api/vote/test/println'  # 替换为你的 API URL
    payload = {
        "type": data_type,
        "url": url,
        "data": data,
        "timestamp": int(time.time() * 1000)
    }

    headers = {
        'Content-Type': 'application/json',
        'Tenant-Id': '1'
    }

    try:
        if data_type == 'received':
            logging.info(f"received data: {data}")  
        response = requests.post(api_url, json=payload, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        logging.info(f"{url} Data sent to API successfully: {response.status_code}")    
    except requests.exceptions.RequestException as e:
        logging.error(f"Failed to send data to API: {e}")

async def log_request_and_response(request, response):
    if request.resource_type != 'xhr':
        return

    timestamp = int(time.time() * 1000)
    response_body = await response.body()
    response_body = response_body.decode('utf-8')
    data = {
        "request": {
            "method": request.method,
            "data": request.post_data,
            "timestamp": timestamp
        },
        "response": {
            "data": {
                "body": response_body
            },
            "timestamp": timestamp
        }
    }
    await send_to_api(json.dumps(data), request.resource_type, request.url)

async def log_ws_messages(websocket):
    logging.warning(f"WebSocket connected to {websocket.url}")
    websocket.on("framereceived", lambda frame: asyncio.create_task(send_to_api(frame, 'received', websocket.url)))
    websocket.on("framesent", lambda frame: asyncio.create_task(send_to_api(frame, 'sent', websocket.url)))

async def run(playwright):
    browser = await playwright.chromium.launch(headless=False)
    context = await browser.new_context()

    pages = [await context.new_page() for _ in sys.argv[1:]]
    urls = sys.argv[1:]

    for page, url in zip(pages, urls):
        logging.warning(f"Navigating to {url}...")
        page.on("websocket", log_ws_messages)
        page.on("response", lambda response: asyncio.create_task(log_request_and_response(response.request, response)))
        await page.goto("https://www.raybet.lol/match/"+url, wait_until="load", timeout=6000000)
        logging.warning(f"Page loaded: {url}")

    # 保持浏览器打开
    await asyncio.sleep(60*60*9)  # 10小时

async def main():
    async with async_playwright() as playwright:
        await run(playwright)

asyncio.run(main())
